﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;
using Ewk.MachineLearning.Classification.Common;
using Ewk.MachineLearning.Persistance.DataAccess;
using Ewk.MachineLearning.Persistance.Domain;

namespace Clustering.MultidimensionalScaling.Web.UI.Controllers
{
    public class DocumentController : TextEntityController<Document>
    {
        // POST api/document
        public async Task PostAsync([FromBody] string value)
        {
            await Task.Factory.StartNew(() =>
                {
                    using (var catalog = CatalogFactory.NewCatalog())
                    {
                        var documentRepository = new TextEntityRepository<Document>(catalog);
                        var document = new Document {Content = value};

                        var wordRepository = new TextEntityRepository<Word>(catalog);
                        var words = value.GetTextEntities(wordRepository);
                        document.LinkToFeatures<Document, Word, WordInDocumentLink>(words);

                        documentRepository.Add(document);
                    }
                });
        }

        // PUT api/document/5
        public async Task PutAsync(Guid id, [FromBody]string value)
        {
            await Task.Factory.StartNew(() =>
                {
                    using (var catalog = CatalogFactory.NewCatalog())
                    {
                        var documentRepository = new TextEntityRepository<Document>(catalog);
                        var document = documentRepository.GetEntityById(id);

                        document.Content = value;
                        document.WordsInDocument = new List<WordInDocumentLink>();

                        var wordRepository = new TextEntityRepository<Word>(catalog);
                        var words = value.GetTextEntities(wordRepository);
                        document.LinkToFeatures<Document, Word, WordInDocumentLink>(words);

                        documentRepository.Update(document);
                    }
                });
        }
    }
}